<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="..\..\node_modules\vue\dist\vue.js"></script>
    <script src="..\..\node_modules\vuex\dist\vuex.js"></script>
</head>
<body>
<div id="app">
    {{ message }}
    {{store.state.count}}
    {{store.getters.than}}
    <p></p>
    <c1></c1>
    <p></p>
    {{store.state.rev}}
    <p></p>
    <button v-on:click="add1">add1</button>
    <button v-on:click="sub1">sub1</button>
    <button v-on:click="add1Direct">add1Direct</button>
</div>
</body>
<script type="application/javascript">
    Vue.use(Vuex);

    var c1 = {
        template:'<p>From ' +
            'C1 {{getCount}} <button v-on:click="a1">add1</button></p>',
        data:function (){
            return {
            };
        },
        computed:{
            getCount:function(){
                return store.state.count;
            }
        },
        methods:{
            a1:function(){
                store.commit('increment');
            }
        }
    };

    var store = new Vuex.Store({
        // 确保修改都来自mutations。导致下面的add1Direct方法执行后控制台输出异常提示。
        strict: true,
        state: {
            count:0,
            rev:0
        },
        mutations:{
            increment(state){
                state.count++;
            },
            sub(state){
                state.count--;
            },
            _rev(state){
                state.rev--;
            }
        },
        getters:{
            "than" : function(state , getters){
                if(state.count > 0){return "greater than 0";}
                if(state.count > 0){return "less than 0";}
                if(state.count = 0){return "equals to 0";}
            }
        },
        plugins:[function(store){
            // 每次 mutation 之后调用
            // mutation 的格式为 { type, payload }
            // 只能通过commit改变state
            store.subscribe((mutation, state) => {
                if(mutation.type != "_rev"){
                    store.commit("_rev");
                }
            })
        }]
    });

    var app_data = {
        message: 'Hello Vue!',
        store
    };

    var app = new Vue({
        el: '#app',
        data: app_data,
        components:{c1:c1},
        methods:{
            add1:function(){
                this.store.commit('increment');
            },
            add1Direct:function(){
                this.store.state.count++;
            },
            sub1:function(){
                this.store.commit('sub');
            }

        },
        computed:{

        },
        watch:{

        },
        created: function () {
            console.log(this.watch);
        }
    });
</script>
</html>